// src/router/index.ts

import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { authRoutes } from "./routes/auth";
import { baseRoutes } from "./routes/base";
import { resetRouter } from "./utils/resetRouter";
import { setupRouterGuards } from './guards';

// 类型定义
export interface DynamicRouteParams {
  roles: string[];
  permissions?: string[];
}

// 基础路由（无需权限）
const staticRoutes: RouteRecordRaw[] = [...authRoutes, ...baseRoutes];

// 获取动态路由模块
function loadRouteModules(): RouteRecordRaw[] {
  const modules = import.meta.glob("./modules/*.ts", { eager: true });
  const routeModuleList: RouteRecordRaw[] = [];
  
  Object.keys(modules).forEach((key) => {
    const mod = (modules[key] as any).default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    routeModuleList.push(...modList);
  });
  
  return routeModuleList;
}

// 创建路由实例（带权限过滤）
export async function createDynamicRouter(params: DynamicRouteParams) {
  // 1. 加载所有可能的路由模块
  const allRoutes = loadRouteModules();
  
  // 2. 根据权限过滤路由
  const accessibleRoutes = await filterRoutesByPermission(
    allRoutes, 
    params.roles,
    params.permissions
  );
  
  // 3. 创建路由实例
  const router = createRouter({
    history: createWebHistory(),
    routes: [...staticRoutes, ...accessibleRoutes]
  });
  
  // 4. 设置守卫
  setupRouterGuards(router);
  
  return router;
}

// 导出默认的静态路由实例（用于初始化）
export const staticRouter = createRouter({
  history: createWebHistory(),
  routes: staticRoutes
});

// 权限过滤函数
async function filterRoutesByPermission(
  routes: RouteRecordRaw[],
  roles: string[],
  permissions?: string[]
): Promise<RouteRecordRaw[]> {
  // 实现你的权限过滤逻辑
  return routes.filter(route => {
    const requiredRoles = route.meta?.roles || [];
    return requiredRoles?.length === 0 || 
           requiredRoles?.some(role => roles.includes(role));
  });
}

// 保留重置方法
export { resetRouter };